﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;

namespace KnBinarySerializer.Field
{
    public static class ILGeneratorExtend
    {      
        public static string FormatWith(this string format, params object[] args)
        {
            //CultureInfo.InvariantCulture
            return string.Format(format, args);
        }
        public static void PushInstance(this ILGenerator il, Type type)
        {
            il.Emit(OpCodes.Ldarg_0);
            if (type.IsValueType)
                il.Emit(OpCodes.Unbox, type);
            else
                il.Emit(OpCodes.Castclass, type);
        }

        public static void BoxIfNeeded(this ILGenerator il, Type type)
        {
            if (type.IsValueType)
                il.Emit(OpCodes.Box, type);
            else
                il.Emit(OpCodes.Castclass, type);
        }
        public static void UnboxIfNeeded(this ILGenerator il, Type type) {
            if (type.IsValueType)
                il.Emit(OpCodes.Unbox_Any, type);
            else
                il.Emit(OpCodes.Castclass, type);
        }

        public static void CallMethod(this ILGenerator il,MethodInfo method)
        {
            if (method.IsFinal || !method.IsVirtual)
                il.Emit(OpCodes.Call, method);
            else
                il.Emit(OpCodes.Callvirt, method);
        }
        
    }
}
